import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../services/constants.dart';
import '../services/token_manager.dart';

class SoldProductScreen extends StatefulWidget {
  @override
  State<SoldProductScreen> createState() => _SoldProductScreenState();
}

class _SoldProductScreenState extends State<SoldProductScreen> {
  List<Map<String, dynamic>> orders = [];
  String userEmail = '';
  bool loading = true;

  @override
  void initState() {
    super.initState();
    _initAndLoad();
  }

  Future<void> _initAndLoad() async {
    final info = await TokenManager.instance.getUserInfo();
    userEmail = info['email'] ?? '';
    await _loadOrders();
  }

  Map<String, String> _headers() => {
        'Content-Type': 'application/json',
        if (userEmail.isNotEmpty) 'email': userEmail,
      };

  Future<void> _loadOrders() async {
    setState(() => loading = true);
    try {
      final url = Uri.parse('${Constants.serverUrl}order/getMySales');
      final res = await http.get(url, headers: _headers());
      if (res.statusCode == 200) {
        final data = jsonDecode(res.body);
        if (data['code'] == 0 && data['data'] is List) {
          orders = List<Map<String, dynamic>>.from(data['data']);
        }
      }
    } catch (_) {}
    setState(() => loading = false);
  }

  Future<void> _deliver(int id) async {
    try {
      final url = Uri.parse('${Constants.serverUrl}order/deliverOrder');
      final res = await http.post(url, headers: _headers(), body: jsonEncode({'id': id}));
      if (res.statusCode == 200) {
        await _loadOrders();
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('已发货')));
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('发货失败: HTTP ${res.statusCode}')));
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('发货失败: $e')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('我卖出的')),
      body: loading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
              onRefresh: _loadOrders,
              child: ListView.separated(
                padding: const EdgeInsets.all(10),
                itemCount: orders.length,
                separatorBuilder: (_, __) => const SizedBox(height: 10),
                itemBuilder: (context, index) {
                  final o = orders[index];
                  final images = (o['goodsImages'] is String)
                      ? (o['goodsImages'] as String)
                          .split(',')
                          .where((e) => e.trim().isNotEmpty)
                          .toList()
                      : <String>[];
                  return Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8)),
                    child: Row(
                      children: [
                        Container(
                          width: 80,
                          height: 80,
                          color: Colors.grey[200],
                          child: images.isNotEmpty ? Image.network(images.first, fit: BoxFit.cover) : Icon(Icons.image_outlined, color: Colors.grey[400]),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text((o['goodsName'] ?? '').toString(), maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500)),
                              const SizedBox(height: 8),
                              Text('¥' + (o['goodsPrice'] ?? '').toString(), style: TextStyle(color: Colors.red[700], fontSize: 16, fontWeight: FontWeight.bold)),
                            ],
                          ),
                        ),
                        if ((o['status'] ?? 0) == 10) ...[
                          const SizedBox(width: 12),
                          OutlinedButton(
                            onPressed: () async {
                              final ok = await showDialog<bool>(
                                context: context,
                                builder: (_) => AlertDialog(
                                  title: const Text('确认发货'),
                                  content: const Text('确定要发货吗？'),
                                  actions: [
                                    TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('取消')),
                                    TextButton(onPressed: () => Navigator.pop(context, true), child: const Text('确定')),
                                  ],
                                ),
                              );
                              if (ok == true) {
                                final id = o['id'] is int ? o['id'] as int : int.tryParse((o['id'] ?? '').toString()) ?? 0;
                                if (id > 0) await _deliver(id);
                              }
                            },
                            child: const Text('发货'),
                          ),
                        ],
                      ],
                    ),
                  );
                },
              ),
            ),
    );
  }
}
